<script setup>
import { onMounted, ref, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';

// 用户信息模型
const UserInfo = ref({
  username: '',
  oldPassword: '',
  newPassword: '',
  rePassword: '',
})

import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
import { useTokenStore } from '@/stores/token'
const tokenStore = useTokenStore()
const token = ref(tokenStore.token)
// 确认两次密码相同
const validateForm = () => {
  if (UserInfo.value.newPassword !== UserInfo.value.rePassword) {
    ElMessage.error('两次密码不一致')
    return false
  }
  return true
}
const router = useRouter();
// 调用接口实现密码修改
import { updatePwd } from '@/apis/user';
const handleSubmit = async () => {
  if (!validateForm()) return
  let result = updatePwd(UserInfo.value);
  ElMessage.success(result.msg ? result.msg : '账号信息更新成功')
  setTimeout(() => {
    router.push('/login');
  }, 500)
}

import { userInfoService, userAvatarUpdateService, uploadFileService } from '@/apis/user';

// 默认图片
const avatar = ref('/placeholder.svg?height=100&width=100')
const imgUrl = ref('')
const previewUrl = ref('')
const fileToUpload = ref(null)


const getImg = async () => {
  let result = await userInfoService();
  imgUrl.value = result.data.userPic;
}

onMounted(() => {
  UserInfo.value.username = userStore.username
  getImg()
})

onUnmounted(() => {
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value)
  }
})

// 头像预览
const handleFileChange = (file) => {
  fileToUpload.value = file
  previewUrl.value = URL.createObjectURL(file.raw)
}

//头像修改
const updateAvatar = async () => {
  const formData = new FormData()
  formData.append('file', fileToUpload.value.raw)
  const uploadData = await uploadFileService(formData);
  const avatarUrl = uploadData.data
  let result = await userAvatarUpdateService(avatarUrl)
  imgUrl.value = avatarUrl
  //调用接口
  let AvatarResult = await userAvatarUpdateService(imgUrl.value);
  ElMessage.success(result.msg || AvatarResult.msg || '修改成功');
  getImg();
}

</script>

<template>
  <el-card class="page-container" :body-style="{ padding: '0px', height: '86.5vh', width: '100vw', display: 'flex', flexDirection: 'row' }" >
    <el-card class="userinfo" >
      <template #header>
        <div class="card-header">
          <span>用户设置</span>
        </div>
      </template>
      <el-form label-position="top">
          <el-form-item label="Avatar">
            <div class="avatar-container">
              <el-avatar :size="200" :src="previewUrl || imgUrl || avatar" /> 
              <el-upload
                ref="uploadRef"
                class="avatar-uploader"
                :show-file-list="false"
                :auto-upload="false"
                action="#"
                :headers="{ 'Authorization': token }"
                :on-change="handleFileChange"
              >
                <el-button class="avatar-button" type="primary">+选择图片</el-button>
                <el-button class="confirm-button" type="primary" @click.stop=updateAvatar()>确认更新</el-button>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="Username">
            <el-input v-model="UserInfo.username" disabled/>
          </el-form-item>
          <el-form-item label="oldPassword">
            <el-input v-model="UserInfo.oldPassword" type="password" />
          </el-form-item>
          <el-form-item label="newPassword">
            <el-input v-model="UserInfo.newPassword" type="password" />
          </el-form-item>
          <el-form-item label="rePassword">
            <el-input v-model="UserInfo.rePassword" type="password" />
          </el-form-item>
          <el-form-item >
            <el-button type="primary" @click="handleSubmit" style="margin: 0 auto;font-size: 14px;height: 35px;">确认更新密码</el-button>
          </el-form-item>
      </el-form>  
    </el-card>
    <el-card class="else-info" >
      <template #header>
        <div class="card-header">
          <span>用户信息</span>
        </div>
      </template>
    </el-card>
  </el-card>
 
</template>

<style scoped>
.userinfo {
  min-height: 100%;
  box-sizing: border-box;
  margin: 0;
  min-width: 280px;

  .head {
    display: flex;

    .card-header {
      text-align: center;
      font-size: 25px;
    }
  }

  .avatar-container {
    width: 200px;
    margin: 0 auto;
  }

  .avatar-button {
    height: 35px;
    font-size: 14px;
  }

  .confirm-button {
    margin-left: 20px;
    font-size: 14px;
    height: 35px;
    background-color: rgba(23, 202, 155, 0.983);
    border: rgba(23, 202, 155, 0.983);
  }

}

.else-info {
  min-height: 100%;
  box-sizing: border-box;
  margin: 0;
  flex: 1;
  /* 让其自动占满剩余空间 */
}
</style>